package com.bigmi.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.bigmi.apis.schedule.CheduleClientIP;
import com.bigmi.model.common.dtos.ResponseResult;
import com.bigmi.model.common.enums.TaskTypeEnum;
import com.bigmi.model.schedule.dto.Task;
import com.bigmi.model.wemedia.pojos.WmNews;
import com.bigmi.utils.common.ProtostuffUtil;
import com.bigmi.wemedia.service.WmNewsScanService;
import com.bigmi.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
@Slf4j
@Service
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Autowired
    private CheduleClientIP cheduleClientIP;

    @Autowired
    private WmNewsScanService wmNewsScanService;

    @Override
    public void addNewsToTask(Integer id, Date publishTime) {
        log.info("添加延时任务----开始");
        Task task =new Task();
        task.setExecuteTime(publishTime.getTime());
        //任务类型
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        //优先级
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        WmNews wmNews =new WmNews();
        wmNews.setId(id);
        //任务类型/序列化
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        cheduleClientIP.addTask(task);
        log.info("添加延时任务----结束");
    }
    //每秒钟拉取一次任务
    @Scheduled(fixedRate = 1000)
    @Override
    public void scanNewTask() {
        log.info("消费任务审核文章");
        ResponseResult responseResult = cheduleClientIP.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (responseResult.getCode().equals(200) && responseResult.getData() != null){
            //将data中数据转为json，task字符串
            String taskString = JSON.toJSONString(responseResult.getData());
            //将task字符串转为task对象
            Task task = JSON.parseObject(taskString, Task.class);
            //反序列化，在task中拿到文章id
            WmNews deserialize = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
            Integer id = deserialize.getId();
            wmNewsScanService.ScanWmNews(id);
        }
    }
}
